package com.jufa_3.dto;

import com.jufa_3.config.WeiXinConfig;
import lombok.Data;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.UUID;


@Data
public class PayInfo {

    private String appid = WeiXinConfig.getAppID();// 小程序ID

    private String mch_id = WeiXinConfig.getMch_id();// 商户号

    private String sign_type = "MD5";//签名类型

    private String notify_url = WeiXinConfig.getNotify_url();  // 通知地址

    private String trade_type = "JSAPI";  // 交易类型

    private String nonce_str;// 随机字符串

    private String sign;// 签名

    private String spbill_create_ip;// 终端IP

    private String out_trade_no;// 商户订单号

    private String detail;      // 商品详情

    private String openid;      // 用户标识

    private String phone_num;   // 电话

    private String body;        // 商品描述

    private String attach;      // 商品描述

    private Integer total_fee;  // 标价金额 ,单位为分

    private  String date;       // 创建时间

    private  String status;

    public PayInfo(String openid, String body, String attach, int total_fee) throws UnknownHostException {
         this.nonce_str = getRandomStringByLength(32);
         this.spbill_create_ip = InetAddress.getLocalHost().getHostAddress();
         this.out_trade_no = get16UUID();
         this.openid = openid;
         this.body = body;
         this.attach = attach;
         this.total_fee = total_fee;
    }

    public PayInfo() throws UnknownHostException {
        this.nonce_str = getRandomStringByLength(32);
        this.spbill_create_ip = InetAddress.getLocalHost().getHostAddress();
        this.out_trade_no = get16UUID();
    }

    public String get16UUID(){
        // 1.开头两位，标识业务代码或机器代码（可变参数）
        String machineId = "JUFA";
        // 2.中间四位整数，标识日期
        SimpleDateFormat sdf = new SimpleDateFormat("MMdd");
        String dayTime = sdf.format(new Date());
        // 3.生成uuid的hashCode值
        int hashCode = UUID.randomUUID().toString().hashCode();
        // 4.可能为负数
        if(hashCode < 0){
            hashCode = -hashCode;
        }
        // 5.算法处理: 0-代表前面补充0; 10-代表长度为10; d-代表参数为正数型
        String value = machineId + dayTime + String.format("%010d", hashCode);
        return value;
    }

    /**
     * 获取一定长度的随机字符串
     *
     * @param length 指定字符串长度
     * @return 一定长度的字符串
     */
    public String getRandomStringByLength(int length) {
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

}
